#! /usr/bin/env node
const pup = require("puppeteer-core")
const { executablePath } = require("./common")
let map = {
  theTimeThePageOpened: { name: "页面打开时间：", value: 0 },
  theTimeOfTheRedirect: { name: "重定向时间：", value: 0 },
  theTimeOfTheDnsQuery: { name: "DNS查询时间：", value: 0 },
  theTimeWhenTheServerConnectionWasEstablished: {
    name: "服务器连接建立的时间：",
    value: 0
  },
  theTimeItTakesForTheDomRenderingToComplete: {
    name: "Dom渲染完成的时间：",
    value: 0
  },
  theTimeOfAppearanceOfTheCoreArea: { name: "核心区域的出现时间：", value: 0 }
}
let times = process.argv[3] || 1
async function run() {
  const browser = await pup.launch({
    executablePath: executablePath
    // 显示浏览器
    // headless: false,
    // 全屏
    // defaultViewport: null
  })
  const page = await browser.newPage()
  const startTime = performance.now()
  await page.goto(process.argv[2] || "https://www.baidu.com/")
  map.theTimeThePageOpened.value =
    map.theTimeThePageOpened.value + performance.now() - startTime
  let timing = JSON.parse(
    await page.evaluate(() => {
      return JSON.stringify(window.performance.timing)
    })
  )
  map.theTimeOfTheRedirect.value =
    map.theTimeOfTheRedirect.value + timing.redirectEnd - timing.redirectStart
  map.theTimeOfTheDnsQuery.value =
    map.theTimeOfTheDnsQuery.value +
    timing.domainLookupEnd -
    timing.domainLookupStart
  map.theTimeWhenTheServerConnectionWasEstablished.value =
    map.theTimeWhenTheServerConnectionWasEstablished.value +
    timing.connectEnd -
    timing.connectStart
  map.theTimeItTakesForTheDomRenderingToComplete.value =
    map.theTimeItTakesForTheDomRenderingToComplete.value +
    timing.domComplete -
    timing.navigationStart

  if (process.argv[4]) {
    try {
      await page.waitForSelector(process.argv[4], { timeout: 3000 }) // 设置超时时间为3秒
      map.theTimeOfAppearanceOfTheCoreArea.value +=
        performance.now() - startTime
    } catch (error) {
      console.log("-----------------------------------------------------")
      console.error("选定的选择器不存在，程序结束!")
      await browser.close()
      process.exit(1) // 结束程序
    }
  }

  await browser.close()
}
;(async () => {
  for (let i = 0; i < times; i++) {
    if (i === 0) {
      console.log("代码运行中...")
      console.log("当前测试网址:" + process.argv[2] || "https://www.baidu.com/")
      console.log("-----------------------------------------------------")
    }
    console.log("当前执行次数：", i + 1)
    await run()
    let keyArray = Object.keys(map)
    if (i === times - 1) {
      console.log("-----------------------------------------------------")
      keyArray.forEach(item => {
        map[item].value = parseFloat((map[item].value / times).toFixed(3))
        console.log(`${map[item].name}${map[item].value}`)
      })
    }
  }
})()
